package com.example.chapter09;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

import com.example.chapter09.service.TestService;

public class ServiceActivity extends AppCompatActivity implements View.OnClickListener {

    private MyServiceConnection connection;  //ServiceConnection对象


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
        findViewById(R.id.btn_service).setOnClickListener(this);
    }



    //绑定服务
    public void btnBinder(View view) {
        if (connection == null) {
            connection = new MyServiceConnection();
        }
        Intent intent = new Intent(this, TestService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    //解绑服务
    public void btnUnbind() {
        if (connection != null) {
            unbindService(connection);
            connection = null;
        }
    }

    //调用绑定服务里面的方法
    public void btnCallServiceInMethod(View view) {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_service) {
            btnBinder(v);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        btnUnbind();
    }

    public class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //如果成功绑定，iBinder为MyService里面的IBinder对象
            Log.i("TestService","服务绑定成功，内存地址为："+iBinder.toString());
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            //解绑
            Log.i("TestService","服务解绑成功");
        }
    }
}